<template>
  <view class="container">
    <view class="message-list">
      <view
        class="message-item"
        v-for="item in messages"
        :key="item.userId"
        @click="goDetail(item.userId)"
      >
        <image class="avatar" :src="item.avatar" />
        <view class="message-content">
          <view class="message-title">{{ item.title }}</view>
          <view class="message-text">{{ item.content }}</view>
        </view>
        <view class="message-time">{{ item.time }}</view>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from "vue";
import { getAllMessages } from "../../api/customerService";

const messages = ref<any[]>([]);
const currentUser = ref(uni.getStorageSync("username"));
const isCustomerService = ref(currentUser.value === "customer_service");

// 获取消息列表
const fetchMessages = async () => {
  const res = await getAllMessages();
  if (res.code === 0) {
    messages.value = res.data;
  }
};

let pollTimer: any = null;

onMounted(() => {
  fetchMessages();
  pollTimer = setInterval(fetchMessages, 3000);
});

onUnmounted(() => {
  if (pollTimer) {
    clearInterval(pollTimer);
  }
});

const goDetail = (userId: string) => {
  if (isCustomerService.value) {
    uni.navigateTo({
      url: `/src/pages/messages/detail?userId=${userId}`,
    });
  } else {
    uni.navigateTo({
      url: `/src/pages/messages/detail?userId=customer_service`,
    });
  }
};
</script>

<style scoped>
.container {
  padding: 16rpx;
}
.message-list {
}
.message-item {
  background: #fff;
  margin-bottom: 12rpx;
  padding: 12rpx;
  border-radius: 8rpx;
  display: flex;
  align-items: center;
}
.avatar {
  width: 48rpx;
  height: 48rpx;
  border-radius: 50%;
  margin-right: 12rpx;
}
.message-content {
  flex: 1;
}
.message-title {
  font-weight: bold;
  font-size: 26rpx;
  margin-bottom: 4rpx;
}
.message-text {
  color: #333;
  font-size: 24rpx;
}
.message-time {
  color: #888;
  font-size: 22rpx;
  margin-left: 8rpx;
  white-space: nowrap;
}
</style>
